<template>
    <div>
        <BreadCrumb name1="商品管理" name2="分类参数"></BreadCrumb>
        <el-card>
            <el-alert title="注意：只允许为第三极分类设置相关参数"  :closable="false" type="warning" show-icon></el-alert>
            <el-row>
                <el-col :span="10">
                    <span>选择商品分类</span>
                    <el-cascader v-model="selectedKeys" :options="goodsCate" :props="{ expandTrigger: 'hover', ...goodsCateOptions }" @change="getGoodsCateChange"></el-cascader>
                </el-col>
            </el-row>
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="动态参数" name="many" :disabled="tabPaneDisabled">
                    <el-row>
                        <el-col :span="4">
                            <el-button type="primary" :disabled="tabPaneDisabled" @click="showAddParamsDialog">添加参数</el-button>
                        </el-col>
                    </el-row>
                    <!-- 动态参数表格 -->
                    <el-table border   stripe :data="manyTableData" style="width: 100%">
                        <el-table-column type="expand">
                            <template slot-scope="scoped">
                                <el-tag v-for="(item,index) in scoped.row.attr_vals" :key="index" closable @close="deleteTag(index,scoped.row)">{{ item }}</el-tag>
                                <el-button @click="ShowInput(scoped.row)" v-if="scoped.row.inputShow == false">添加tag</el-button>
                                <el-input ref="inputRef" v-model="scoped.row.inputValue" v-else>
                                    <el-button slot="append" icon="el-icon-check" @click="AddTag(scoped.row)"></el-button>
                                </el-input>
                            </template>
                        </el-table-column>
                        <el-table-column type="index" label="#"></el-table-column>
                        <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scoped">
                                <el-button type="primary" icon="el-icon-edit" @click="ShowUpdateDialog(scoped.row)">编辑</el-button>
                                <el-button type="danger" icon="el-icon-delete" @click="ShowDeleteConfirm(scoped.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态参数" name="only" :disabled="tabPaneDisabled">
                    <el-row>
                        <el-col :span="4">
                            <el-button type="primary" :disabled="tabPaneDisabled" @click="showAddParamsDialog">添加参数</el-button>
                        </el-col>
                    </el-row>
                    <!-- 静态参数表格 -->
                    <el-table border  stripe :data="onlyTableData" style="width: 100%">
                        <el-table-column type="expand"></el-table-column>
                        <el-table-column type="index" label="#"></el-table-column>
                        <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scoped">
                                <el-button type="primary" icon="el-icon-edit" @click="ShowUpdateDialog(scoped.row)">编辑</el-button>
                                <el-button type="danger" icon="el-icon-delete" @click="ShowDeleteConfirm(scoped.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
            <!-- 添加对话框 -->
            <el-dialog :title="'添加'+titleText" :visible.sync="AddParamsDialogVisible" width="30%">
                <el-form ref="AddParamsFormRef" :model="AddParamsForm" :rules="AddParamsFormRules" label-width="80px">
                    <el-form-item label="参数名称" prop="attr_name">
                        <el-input v-model="AddParamsForm.attr_name"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="AddParamsDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="AddParams">确 定</el-button>
                </span>
            </el-dialog>
            <!-- 编辑参数信息 -->
            <el-dialog :title="'编辑'+titleText" :visible.sync="UpdateParamsDialogVisible" width="30%">
                <el-form ref="UpdateParamsFormRef" :model="GetParamsForm" :rules="AddParamsFormRules" label-width="80px">
                    <el-form-item label="参数名称" prop="attr_name">
                        <el-input v-model="GetParamsForm.attr_name"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="UpdateParamsDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="UpdateParams">确 定</el-button>
                </span>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
import BreadCrumb from '@/components/BreadCrumb';
import {Get_GoodsData} from '@/api/goods.js';
import {Get_CateParams,Add_CateParams,Get_OneParams,Update_OneParams,Delete_OneParams} from '@/api/params.js';
    export default {
        data(){
            return{
                goodsCate:[],// 级联选择器选中的值
                selectedKeys:[],// 级联选择器中渲染的值
                goodsCateOptions:{// props配置
                    label:'cat_name',
                    value:'cat_id',
                    children:'children'
                },
                activeName: 'many', // tab v-model 使用绑定的数据
                manyTableData:[],//动态参数表格
                onlyTableData:[],//静态参数表格
                AddParamsDialogVisible:false,//控制添加参数对话框的显示与隐藏
                UpdateParamsDialogVisible:false,//控制编辑参数对话框的显示与隐藏
                AddParamsForm:{//添加参数的绑定初始值
                    attr_name:''
                },
                AddParamsFormRules:{//添加参数的校验规则
                    attr_name:[
                        { required: true, message: '请输入参数名称', trigger: 'blur' }
                    ]
                },
                AddTagValue:'',
                GetParamsForm:{},//获取参数初始值
                UpdateParamsForm:{
                    attr_id:''
                }
            }
        },
        components:{
            BreadCrumb
        },
        mounted(){
            this.getGoodsData();//获取所有参数列表
        },
        methods:{
            // 获取级联选择器中的数据
            async getGoodsData(){
                const result = await Get_GoodsData({type:3});//获取三级的参数列表
                console.log(result);
                if(result.meta.status != 200){//如果状态码不为200 返回错误提示框
                    return this.$message.error('请求失败')
                }
                this.goodsCate = result.data;//否则赋初始值
            },
            // 标签页改变时触发
            handleClick(tab, event) {
                console.log(tab, event);
                this.getCateParams();//再次执行获取参数请求
            },
            // 获取参数
            async getCateParams(){
                const result = await Get_CateParams({
                    method:"get",
                    url:`categories/${this.cat_id}/attributes`,
                    params:{
                        sel:this.activeName
                    }
                })
                console.log(result);
                result.data.forEach((item)=>{//遍历result.data
                    item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];//将数组切割
                    item.inputValue = '';//添加当添加tag时绑定的value值
                    item.inputShow = false;//控制显示与隐藏
                })
                if(result.meta.status != 200){//如果状态码不为200 弹出错误提示框
                    return this.$message.error('请求失败')
                }
                if(this.activeName == 'many'){//如果activeName为many
                    this.manyTableData = result.data//将数据赋值给manyTableData
                }else{//如果activeName为only
                    this.onlyTableData = result.data//将数据赋值给onlyTableData
                }
            },
            // 当级联选择器改变时触发
            getGoodsCateChange(){
                console.log(this.selectedKeys);
                console.log(this.cat_id);
                this.getCateParams();//重新发送请求
            },
            // 显示添加参数对话框
            showAddParamsDialog(){
                this.AddParamsDialogVisible = true;
            },
            // 添加参数
            AddParams(){
                this.$refs.AddParamsFormRef.validate(async(valid)=>{//检验表单
                    if(valid){//valid值为布尔值 如果为true
                        const result = await Add_CateParams({//发送添加请求
                            method:'post',
                            url:`categories/${this.cat_id}/attributes`,
                            data:{
                                attr_name:this.AddParamsForm.attr_name,
                                attr_sel:this.activeName
                            }
                        })
                        console.log(result);
                        if(result.meta.status != 201){//如果状态码不为200 弹出错误提示框
                            return this.$message({
                                message:'添加失败',
                                type:'error'
                            })
                        }
                        this.getCateParams();//重新调用获取所有参数的请求
                        this.$refs.AddParamsFormRef.resetFields();//清空form表单的值
                        this.AddParamsDialogVisible = false;//将对话框隐藏
                    }
                })
            },
            // 显示input框
            ShowInput(info){
                info.inputShow = true;
                this.$nextTick(()=>{//$nextTick获取dom更新后的值
                    this.$refs.inputRef.focus();//让input框获取焦点
                })
            },
            // 添加tag
            AddTag(info){
                console.log(info);
                console.log(info.inputValue);
                info.attr_vals.push(info.inputValue);//将input框内的值添加到attr_vals
                info.inputValue = '';//清空input框
                this.updateTag(info);//调用请求
                info.inputShow = false;//将input隐藏
            },
            // 删除tag
            deleteTag(index,info){
                info.attr_vals.splice(index,1);//删除 第一个参数 起始位置index 第二个参数 删除个数
                this.updateTag(info);//调用请求
            },
            // 更改tag 添加 删除
            async updateTag(info){
                const newAttr_vals = info.attr_vals.join(',');//先将数组转为字符串 以 , 分隔
                console.log(newAttr_vals);
                const result = await Update_OneParams({//发送更改请求
                    method:'put',//请求方式为put
                    url:`categories/${this.cat_id}/attributes/${info.attr_id}`,//请求路径
                    data:{//请求体参数
                        attr_name:info.attr_name,
                        attr_sel:this.activeName,
                        attr_vals:newAttr_vals
                    }
                })
                console.log(result);
                if(result.meta.status != 200){//如果状态码不为200
                    return this.$message.error('修改失败')//返回错误提示框
                }
                this.$message({//否则弹出成功提示框
                    message:'修改成功',
                    type:'success'
                })
            },
            // 获取参数信息
            async ShowUpdateDialog(info){
                this.UpdateParamsForm.attr_id = info.attr_id;//存储id
                const result = await Get_OneParams({//发送请求
                    method:'get',//请求方式
                    url:`categories/${info.cat_id}/attributes/${info.attr_id}`,//请求路径
                    params:{//请求参数
                        attr_sel:this.activeName
                    }
                })
                console.log(result);
                if(result.meta.status != 200){//如果状态码不为200 返回错误提示框
                    return this.$message.error('获取失败')
                }
                this.GetParamsForm = result.data;//否则 将数据赋初始值
                this.UpdateParamsDialogVisible = true;//将当前对话框显示
            },
            // 编辑参数信息
            async UpdateParams(){
                const result = await Update_OneParams({//发送请求
                    method:'put',//请求方式
                    url:`categories/${this.cat_id}/attributes/${this.GetParamsForm.attr_id}`,//请求路径
                    data:{//请求参数
                        attr_name:this.GetParamsForm.attr_name,
                        attr_sel:this.activeName
                    }
                })
                console.log(result);
                if(result.meta.status != 200){//如果状态码不为200 返回错误提示框
                    return this.$message.error('编辑失败')
                }
                this.GetParamsForm = result.data;//否则赋初始值
                this.getCateParams();//调用获取所有参数请求 更新数据
                this.UpdateParamsDialogVisible = false;//将对话框隐藏
            },
            // 删除参数信息
            async ShowDeleteConfirm(info){
                const confirmResult = await this.$confirm('此操作将永久删除该用户信息，是否继续？','提示',{//弹出确认框
                    confirmButtonText:'确定',//确认按钮文字
                    cancelButtonText:'取消'//取消按钮文字
                }).catch(err=>err);//catch获取错误信息
                if(confirmResult == 'confirm'){//判断confirmResult的值如果为confirm发送请求
                    const result = await Delete_OneParams({//发送请求
                        method:'delete',//请求方式
                        url:`categories/${this.cat_id}/attributes/${info.attr_id}`//请求路径
                    })
                    console.log(result);
                    if(result.meta.status != 200){//如果状态码不为200 弹出错误提示框
                        return this.$message.error('删除失败')
                    }
                    this.$message.success('删除成功');//否则弹出成功提示框
                    this.getCateParams();//调用获取所有参数请求 更新数据
                }
            }
        },
        computed:{
            // 设置禁用功能
            tabPaneDisabled(){
                return this.selectedKeys.length > 0 ? false : true//如果选中的数组长度大于0就为不禁用 否则为true禁用
            },
            // 设置id为最新值
            cat_id(){
                return this.selectedKeys[this.selectedKeys.length - 1]
            },
            // 设置title文字
            titleText(){
                return this.activeName == 'many' ? '动态参数' : '静态参数'
            }
        }
    }
</script>

<style lang="scss" scoped>
.el-alert{
    margin-bottom:10px;
}
.el-cascader{
    margin-left:10px;
}
.el-tag{
    margin:5px;
}
</style>